import { defineStore } from "pinia";
import {
  getSearchList,
  getForm,
  addData,
  editData,
  deleteData,
  getTableColumns,
  getTableBody,
  getSelectList,
  clearCache,
} from "@/services/intelligentAssistant.service";
import { message, Modal } from "ant-design-vue";
import { cloneDeep } from "lodash";
import moment from "moment";
export const modalValueIframe = defineStore("modal-value-iframe", {
  state: () => {
    return {
      commentForm: {
        comment_status: undefined,
        comment_text: "",
        comment_time: "",
      },
      commentVisible: false,
      backId: "",
      commentTitle: "评审",
      searchList: [], //查询条件
      formKey: [], //表单item
      formData: {}, //表单回显
      columns: [],
      tableData: [],
      option: [],
      deleteId: [], //批量删除选中项
      id: "",
      userId: "",
      dimensionCodeId: "",
      searchData: {},
      pageNo: 1,
      pageSize: 10,
      total: 0,
      dimCode: "",
      visible: false,
      visiblePreview: false,
      disable: false,
      title: "查看-维度管理单",
      largeValue: "", //当前最大的维度编码用于自增
      dimensionCode: "",
      tableName: "",
      backList: {}, //选择项数据
      editNameBack: "", //编辑备份名称
    };
  },
  getters: {
    codeList() {
      let arr = [];
      if (this.deleteId.length > 0) {
        this.deleteId.forEach((item) => {
          arr.push(this.backList[item]);
        });
      } else {
        arr = [];
      }
      return arr;
    },
  },
  actions: {
    //提交评审操作
    async userComment() {
      let list =
        this.commentTitle !== "批量评审"
          ? this.backId
          : this.deleteId.join(",");
      let time = moment().format("YYYY-MM-DD HH:mm:ss");
      let obj = {
        ...this.formData,
        ...this.commentForm,
        comment_time: time,
      };
      const res = await editData({
        id: this.id,
        formData: obj,
      });
      if (res && res?.code === 200) {
        message.success("评审成功", 2);
        await this.clearCacheSql([this.formData[this.formKey[0].key]]);
        this.cancelCommentModal();
        await this.getTbodyData();
      } else {
        message.error(res?.result || "评审失败");
      }
    },
    //打开评审弹窗
    openCommentModal(record, type) {
      if (!type && this.deleteId.length === 0) {
        return Modal.info({
          title: "提示",
          content: "至少选择一条数据",
          centered: true,
        });
      }
      this.previewDataOperation(record);
      if (type) {
        this.commentForm = {
          comment_status:
            record?.comment_status === "-1"
              ? undefined
              : record?.comment_status || undefined,
          comment_text: record?.comment_text || "",
          comment_time: record?.comment_time || "",
        };
        this.backId = record.id;
        this.commentTitle = "评审";
      } else {
        this.commentForm = {
          comment_status: undefined,
          comment_text: "",
          comment_time: "",
        };
        this.commentTitle = "批量评审";
      }
      this.commentVisible = true;
    },
    //关闭评审
    cancelCommentModal() {
      this.commentVisible = false;
      this.backId = "";
      this.commentForm = {
        comment_status: undefined,
        comment_text: "",
        comment_time: "",
      };
      this.commentTitle = "评审";
    },
    updateCommentFormData(key, value) {
      this.commentForm[key] = value;
      this.commentForm = { ...this.commentForm };
    },
    async clearCacheSql(params) {
      await clearCache({ dim: params });
    },
    async getSearchData() {
      const res = await getSearchList(this.id);
      if (res.code === 200) {
        const { properties, searchFieldList } = res.result;
        let arr = [];
        searchFieldList.forEach((item) => {
          const { title, view } = properties[item];
          arr.push({
            title,
            view,
            key: item,
          });
        });
        arr.forEach((item) => {
          if (item.view === "sel_search" || item.view === "list") {
            this.searchData[item.key] = undefined;
          } else {
            this.searchData[item.key] = "";
          }
        });

        this.searchList = [...arr];
      }
    },
    async getFormList() {
      const res = await getForm(this.id);
      if (res.code === 0) {
        let properties = res.result?.schema?.properties;
        this.tableName = res.result?.schema?.table;
        if (properties) {
          let arr = [];
          for (let key in properties) {
            arr.push({
              key: key,
              ...properties[key],
            });
          }
          this.formKey = arr.sort((a, b) => {
            return a.order - b.order;
          });
        }
      }
    },
    //新增保存
    async addDataObj() {
      this.formData["comment_status"] = "-1";
      const res = await addData({
        id: this.id,
        formData: this.formData,
      });
      if (res.code === 200) {
        message.success(res.message, 2);
      } else {
        message.error((res && res?.message) || "新增失败", 2);
      }
      return (res && res?.code) || 400;
    },
    //编辑报存
    async editDataObj() {
      const res = await editData({
        id: this.id,
        formData: this.formData,
      });
      if (res.code === 200) {
        message.success(res.result, 2);
        await this.clearCacheSql([this.formData[this.formKey[0].key]]);
      } else {
        message.error((res && res?.result) || "编辑失败", 2);
      }
      return (res && res?.code) || 400;
    },
    async submit() {
      if (this.title.includes("修改")) {
        await this.editDataObj().then(async (code) => {
          if (code === 200 || code === 0) {
            await this.offModal();
            await this.getTbodyData();
          }
        });
      } else {
        await this.addDataObj().then(async (code) => {
          if (code === 200 || code === 0) {
            await this.offModal();
            await this.getTbodyData();
          }
        });
      }
    },
    //新增操作
    addDataOperation(title) {
      let obj = {};
      this.formKey.forEach((item) => {
        if (item.view === "sel_search") {
          obj[item.key] = undefined;
        } else {
          obj[item.key] = "";
        }
      });
      if ("editor" in obj) {
        obj["editor"] = this.userId;
      }
      if ("update_time" in obj) {
        obj["update_time"] = moment().format("YYYY-MM-DD HH:mm:ss");
      }
      if (this.dimensionCode && this.dimensionCode in obj) {
        let dimension = this.largeValue.split("_");
        if (dimension.length > 1) {
          obj[this.dimensionCode] =
            dimension[0] + "_000" + (parseFloat(dimension[1]) + 1);
        } else {
          if (this.tableData.length > 0) {
            obj[this.dimensionCode] = "";
          } else {
            obj[this.dimensionCode] = "D_0001";
          }
        }
      }
      this.formData = { ...obj };
      this.visible = true;
      this.disable = false;
      this.title = title;
    },
    offModal() {
      let obj = {};
      this.formKey.forEach((item) => {
        if (item.view === "sel_search") {
          obj[item.key] = undefined;
        } else if (item.view === "date") {
          obj[item.key] = null;
        } else {
          obj[item.key] = "";
        }
      });
      this.formData = { ...obj };
      this.visible = false;
    },
    //编辑操作
    editDataOperation(record, type, title, status) {
      let obj = cloneDeep(record);
      console.log(obj, "obj");
      if ("editor" in obj && status) {
        obj["editor"] = this.userId;
      }
      if ("update_time" in obj) {
        obj["update_time"] = moment().format("YYYY-MM-DD HH:mm:ss");
      }
      this.formData = { ...obj };
      this.visible = true;
      if (type) {
        this.disable = true;
      } else {
        this.disable = false;
      }
      this.editNameBack = record[this.formKey[1].key];
      this.title = title;
    },
    previewDataOperation(record, type, title, status) {
      let obj = cloneDeep(record);
      this.formData = { ...obj };
      if (type) {
        this.disable = true;
      } else {
        this.disable = false;
      }
      this.editNameBack = record[this.formKey[1].key];
      if (title) {
        this.title = title;
        this.visiblePreview = true;
      }
    },
    //删除
    async deleteDataObj(record, type) {
      let that = this;
      if (!type && this.deleteId.length === 0) {
        return Modal.info({
          title: "提示",
          content: "至少选择一条数据",
          centered: true,
        });
      }
      Modal.confirm({
        title: "提示",
        content: "确定删除选中数据吗",
        okText: "确定",
        cancelText: "取消",
        centered: true,
        onOk() {
          return new Promise((resolve, reject) => {
            deleteData({
              id: that.id,
              deleteId: type ? record.id : that.deleteId.join(","),
            }).then((res) => {
              if (res.code === 200) {
                //关闭弹窗
                resolve();
                let params = type
                  ? [record[that.formKey[0].key]]
                  : that.codeList;
                that.getTbodyData();
                that.clearCacheSql(params);
                message.success(res.result, 2);
              } else {
                //不关闭弹窗
                reject();
                message.error(res.result || "指标分类删除失败", 2);
              }
            });
          });
        },
        onCancel() {},
      });
    },
    async getTheadData() {
      const res = await getTableColumns(this.id);
      if (res.code === 0) {
        if (res.result.columns.length > 0) {
          let obj = {
            title: "操作",
            dataIndex: "operate",
            align: "center",
            fixed: "right",
            scopedSlots: { customRender: "operate" },
          };
          this.columns = res.result.columns
            .filter(
              (item1) =>
                item1.dataIndex !== "comment_text" &&
                item1.dataIndex !== "comment_time" &&
                item1.dataIndex !== "fill_note"
            )
            .map((item, index) => {
              if (index === 0) {
                return {
                  title: item.title,
                  dataIndex: item.dataIndex,
                  align: "center",
                  fixed: "left",
                  ellipsis: true,
                  width: 150,
                };
              } else if (item.dataIndex === "dim_lvl_1_code") {
                return {
                  title: item.title,
                  dataIndex: item.dataIndex,
                  align: "center",
                  ellipsis: true,
                  scopedSlots: { customRender: "dimensionName" },
                };
              } else if (item.dataIndex === "comment_status") {
                return {
                  title: "评审状态",
                  dataIndex: "comment_status",
                  align: "center",
                  ellipsis: true,
                  scopedSlots: { customRender: "comment_status" },
                };
              } else {
                return {
                  title: item.title,
                  dataIndex: item.dataIndex,
                  align: "center",
                  ellipsis: true,
                };
              }
            });
          this.dimensionCode = this.columns[0]?.dataIndex;
          this.columns.push(obj);
        }
      }
    },
    async getTbodyData() {
      let params = cloneDeep(this.searchData);
      console.log(params, "弹窗参数");
      let arr = [];
      for (let key in params) {
        if (!params[key]) {
          delete params[key];
        } else {
          arr.push({
            field: key,
            rule: "like",
            val: params[key],
            type: "text",
            dbType: "string",
          });
        }
      }
      let len = Object.keys(params).length;
      const res = await getTableBody({
        id: this.id,
        searchData: {
          superQueryParams: !len ? "" : arr,
          pageNo: this.pageNo,
          pageSize: this.pageSize,
          buttonGroup: "",
          superQueryMatchType: !len ? "" : "and",
          hasQuery: !len ? "" : true,
        },
      });
      if (res.code === 0) {
        this.total = res.result.total || 0;
        this.largeValue = res.result?.largeValue || "";
        this.tableData = res.result?.records || [];
      } else {
        this.total = 0;
        this.largeValue = "";
        this.tableData = [];
      }
    },
    //查询
    async search() {
      this.deleteId = [];
      if (this.pageNo === 1) {
        await this.getTbodyData();
      } else {
        this.pageNo = 1;
      }
      await this.getSelectData();
    },
    updateSearchData(key, value) {
      this.searchData[key] = value;
      this.searchData = { ...this.searchData };
    },
    updateFormData(key, value) {
      this.formData[key] = value;
      this.formData = { ...this.formData };
    },
    updateDeleteId(selectArr, arrList) {
      this.deleteId = selectArr;
      if (selectArr.length > 0) {
        arrList.forEach((item, index) => {
          // eslint-disable-next-line no-prototype-builtins
          if (!this.backList.hasOwnProperty(item.id)) {
            this.backList[item.id] = item[this.formKey[0].key];
          }
        });
      } else {
        this.backList = {};
      }
    },
    async getSelectData() {
      const res = await getSelectList({
        dimCode: this.dimCode,
      });
      if (res.code === 200) {
        this.option = res.result;
      } else {
        this.option = [];
      }
    },
  },
});
